package features.advance.proxy;

import lombok.extern.slf4j.Slf4j;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.charset.StandardCharsets;
import java.security.Security;
import java.util.Arrays;
import java.util.Base64;

/**
 * 
 * @author LIN
 * @date 2023-01-07 11:14
 */
@Slf4j
public class Aes128Util {

    private static final String KEY = "e18ee185c8d9cbdc";

    private static final String IV=  "Ekjp8PQQR25jzG4E";


    public static String AESDecode(String content){
        try{
            byte[] bytes = KEY.getBytes(StandardCharsets.UTF_8);
            Security.addProvider(new BouncyCastleProvider());
            SecretKeySpec aes = new SecretKeySpec(bytes, "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");

            IvParameterSpec ivParameterSpec = new IvParameterSpec(IV.getBytes());
            cipher.init(Cipher.DECRYPT_MODE,aes,ivParameterSpec);
            try{
                byte[] decode = Base64.getDecoder().decode(content);
                byte[] original = cipher.doFinal(decode);
                return  new String(original,StandardCharsets.UTF_8);
            }catch(Exception e){
                log.debug(e.getMessage());
                return null;
            }


        }catch(Exception e){
            log.debug(e.getMessage());
            return null;
        }
    }


    public static void main(String[] args) {
        byte[] bytes = "e18ee185c8d9cbdc".getBytes();
        System.out.println(Arrays.toString(bytes));
        File file = new File("D:\\project-2022\\yqjr\\pythonProject\\a\\a.ts");
        File file1 = new File("D:\\project-2022\\yqjr\\pythonProject\\a\\b.ts");
        try {
            FileInputStream inputStream = new FileInputStream(file);
            FileOutputStream outputStream = new FileOutputStream(file1);
            int r = -1;
            byte[] data = new byte[1024*1024];
            while((r=inputStream.read(data))!=-1){
                String s = AESDecode(new String(data, 0, r,StandardCharsets.UTF_8));
                outputStream.write(s.getBytes());
            }

            inputStream.close();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
